package com.sxbbc.plat.controller.jz;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.statics.FunctionUtils;
import com.sxbbc.common.basics.wx.util.WeixinUtil;
import com.sxbbc.common.core.alipay.AliCallBackUrls;
import com.sxbbc.common.core.alipay.AlipayNotify;
import com.sxbbc.common.core.alipay.AlipayUtils;
import com.sxbbc.common.core.entity.jz.CPayLog;
import com.sxbbc.common.core.entity.jz.InfoAli;
import com.sxbbc.common.core.service.ICPayLogService;
import com.sxbbc.common.core.service.system.pay.PayService;
import com.sxbbc.common.core.utils.RedisUtils;
import com.sxbbc.common.core.wx.WxCallBackUrls;

/**
 * 支付回调处理controller
 *
 * @author xiaoky
 * @date 2019-07-08
 */
@RestController
public class PayController {
    private static Logger logger = Logger.getLogger(PayController.class);
    @Autowired
    private PayService payService;
    @Autowired
    private ICPayLogService icPayLogService;

    /***************************微信支付回调****************************/
    /**
     * 微信支付回调——同步回调
     *
     * @param paycode
     * @param transcode
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = WxCallBackUrls.SYNCHRO_URL)
    public RestResponse wxpaySynchro(String paycode, String transcode) {
        RestResponse result = null;
        try {
            payService.handlePayCallBack(paycode, transcode);
        } catch (Exception e) {
            return GetRest.getFail(e.getMessage());
        }
        return result;
    }

    /**
     * 微信支付回调——异步回调
     *
     * @param request
     * @param response
     * @author xiaoky
     */
    @RequestMapping(value = WxCallBackUrls.ASYNCHRO_URL)
    public void wxpayNotice(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("微信支付回调");
        Map<String, String> map = WeixinUtil.xmlToMap(request);
        logger.info("微信支付异步回调接收MAP" + map);
        //获取支付返回结果
        String return_code = map.get("return_code");
        //如果是支付成功
        if ("SUCCESS".equals(return_code.toUpperCase())) {
            //本系统的交易单号
            String paycode = map.get("out_trade_no");
            //微信生成的交易单号
            String transaction_id = map.get("transaction_id");
            //支付成功 回调
            try {
                payService.handlePayCallBack(paycode, transaction_id);
            } catch (Exception e) {
                logger.info("打印微信异步回调异常" + e.getMessage());
            }
        }
        //回调之后 发送消息给微信通知已经接收到结果
        FunctionUtils.getWriter(response, return_code);
    }


    /***********************************支付宝支付回调************************************/
    /**
     * 支付宝异步回调
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     * @author xiaoky
     */
    @RequestMapping(value = AliCallBackUrls.ASYNCHRO_URL)
    public void handleAlipay(HttpServletRequest request, HttpServletResponse response){
        Map<String, String> map = AlipayUtils.getReturnMap(request);
        logger.info("进入支付宝支付异步回调获取结果集MAP" + map);
        //获取支付返回结果
        String trade_status = map.get("trade_status");
        InfoAli aliInfo = RedisUtils.getInstance().getAliInfo();
        //本系统的交易单号
        String payCode = map.get("out_trade_no");
        //验证支付宝结果
        String url = "";
        QueryWrapper<CPayLog> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_code", payCode);
        CPayLog cPayLog = icPayLogService.getOne(wrapper);
        if (cPayLog != null) {
            //根据渠道判断返回去的链接地址
			//url=Configue.infoDomain.getPcurl()+ReturnUrl.Pc.ORDER_URL;
			//if(FunctionUtils.isEquals(PaychannlEnums.mobile.getId(), cPayLog.getPaychannel())){
			//	url=Configue.infoDomain.getWxurl()+ReturnUrl.Moblie.ORDER_URL;
			//}else if(FunctionUtils.isEquals(PaychannlEnums.unline.getId(), cPayLog.getPaychannel())){
			//	url=Configue.infoDomain.getWxurl()+ReturnUrl.Moblie.showResult;
			//}
        }
        if (AlipayNotify.verify(map, aliInfo)) {
            logger.info("支付宝异步回调验签成功");
            //如果是支付成功
            if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                //支付宝生成的交易单号
                String transactionId = map.get("trade_no");
                try {
                    payService.handlePayCallBack(payCode, transactionId);
                    response.sendRedirect(url);
                } catch (Exception e) {
                    logger.info("答应支付宝支付异步回调异常" + e.getMessage());
                }
            }
        }
    }

    /**
     * 支付宝支付  同步通知订单支付完成异步回调方法
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = AliCallBackUrls.SYNCHRO_URL)
    public ModelAndView handleSysAlipay(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = AlipayUtils.getReturnMap(request);
        logger.info("进入支付宝同步回调获取结果集MAP" + map);
        //获取支付返回结果

        String tradeStatus = map.get("trade_status");
        InfoAli aliInfo = RedisUtils.getInstance().getAliInfo();
        //本系统的交易单号
        String payCode = map.get("out_trade_no");
        String url = "";
        QueryWrapper<CPayLog> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_code", payCode);
        CPayLog cPayLog = icPayLogService.getOne(wrapper);
        if (cPayLog != null) {
            //根据渠道判断返回去的链接地址

        }
        //验证支付宝结果
        if (AlipayNotify.verify(map, aliInfo)) {
            logger.info("支付宝异步回调验签成功");
            //如果是支付成功
            if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
                //支付宝生成的交易单号
                String transaction_id = map.get("trade_no");
                //支付成功 回调
                try {
                    payService.handlePayCallBack(payCode, transaction_id);
                    logger.info("支付宝回调成功重定向URL:");
                    url = "";
                } catch (Exception e) {
                    logger.info("支付宝支付回调异常" + e.getMessage());
                }
            }
        }
        if (StringUtils.isBlank(url)) {
            throw new ThrowJsonException("订单处理失败");
        }
        ModelAndView view = new ModelAndView("redirect:" + url);
        return view;
    }
    
    @RequestMapping(value="/payBack")
    @ResponseBody
    public RestResponse payBack() {
    	String paycode="OL93194581892633";
    	String transaction_id="201910120906";
        try {
            payService.handlePayCallBack(paycode, transaction_id);
        } catch (Exception e) {
        	e.printStackTrace();
        	return GetRest.getFail(e.getMessage());
        }
    	return GetRest.getSuccess("SUCCESS");
    }
}
